package models

import (
	"fmt"
	"go-admin-official/modules/database"
)

type DonationsModel struct {
	Base `json:"-"`

	Id           int64  `json:"id"`
	Name         string `json:"name"`
	Amount       int64  `json:"amount"`
	AmountWord   string `json:"amount_word"`
	Channel      int64  `json:"channel"`
	ChannelWord  string `json:"channel_word"`
	DonationTime string `json:"donation_time"`
}

func Donations() DonationsModel {
	return DonationsModel{Base: Base{Table: "donations"}}
}

func (t DonationsModel) WithTx(tx *database.SqlTx) DonationsModel {
	t.Tx = tx
	return t
}

func (t DonationsModel) Find(id interface{}) DonationsModel {
	item, _ := database.Table(t.Table).Find(id)

	if item == nil {
		return Donations()
	}

	return t.MapToModel(item)
}

func (t DonationsModel) List() []DonationsModel {
	all, _ := database.Table(t.Table).OrderBy("donation_time", "desc").All()
	data := make([]DonationsModel, len(all))
	for k, item := range all {
		data[k] = t.MapToModel(item)
	}
	return data
}

func (t DonationsModel) Update(key string, value interface{}) (int64, error) {
	return database.Table(t.Table).
		Where("id", "=", t.Id).
		Update(database.H{
			key: value,
		})
}

func (t DonationsModel) IsEmpty() bool {
	return t.Id == int64(0)
}

func (t DonationsModel) IsNotEmpty() bool {
	return t.Id != int64(0)
}

func (t DonationsModel) MapToModel(m map[string]interface{}) DonationsModel {
	t.Id, _ = m["id"].(int64)
	t.Name, _ = m["name"].(string)
	t.Amount, _ = m["amount"].(int64)
	t.AmountWord = fmt.Sprintf("%.2f", float32(t.Amount)/100)
	t.Channel, _ = m["channel"].(int64)
	if t.Channel == int64(0) {
		t.ChannelWord = "微信"
	} else if t.Channel == int64(1) {
		t.ChannelWord = "支付宝"
	} else {
		t.ChannelWord = "其他"
	}
	t.DonationTime, _ = m["donation_time"].(string)
	return t
}
